<?php
/**
 * Cart
 * Created by Veyron
 * motto:现在的拼搏 为了更好的明天
 * day:  2020/3/25
 * Time: 15:46
 */

namespace app\common\business;

use app\common\lib\Arr;
use app\common\lib\Key;
use Symfony\Component\VarDumper\Command\Descriptor\DumpDescriptorInterface;
use think\Exception;
use think\facade\Cache;

class Cart extends BusBase
{
    public function insertRedis($userId, $id, $num){
        //id获取商品数据
        $goodsSku = (new GoodsSku())->getNormalSkuAndGoods($id);
        if(!$goodsSku){
            return FALSE;
        }
        $data = [
            'title'         => $goodsSku['goods']['title'],
            'image'         => $goodsSku['goods']['recommend_image'],
            'num'           => $num,
            'goods_id'      => $goodsSku['goods']['id'],
            'create_time'   => time()
        ];

        try {
            //查询商品是否存在
            $get = Cache::hGet(Key::userCart($userId), $id);

            if($get){
                $get = json_decode($get, true);
                $data['num'] = $data['num'] +  $get['num'];
            }
            //注意添加库存判断
            // todo...
            $res = Cache::hSet(Key::userCart($userId), $id, json_encode($data));
        }catch (\Exception $e){
            return FALSE;
        }
        return $res;

    }
    public function lists($userId, $ids){
        try {
            if($ids){
                $ids = explode(',',$ids);
                $res = Cache::hMGet(Key::userCart($userId),$ids);
                //找不到记录返回false,有false直接返回空数组
                if(in_array(false,array_values($res))){
                    return [];
                }
            }else{
                $res = Cache::hGetAll(Key::userCart($userId));
            }
        }catch (\Exception $e){
            return FALSE;
        }
        if(!$res){
            return [];
        }
        $result = [];
        $ids = array_keys($res);
        $skus = (new GoodsSku())->getNormalInIds($ids);
        //检查库存
        $stocks = array_column($skus,'stock','id');

        $skusPrice = array_column($skus, 'price', 'id');
        $skusSpecsValueIds = array_column($skus, 'specs_value_ids', 'id');
        $skusValues = (new SpecsValue())->dealSpecsValue($skusSpecsValueIds);

        foreach ($res as $k => $v){
            $prcie = $skusPrice[$k] ?? 0;
            $v = json_decode($v, true);
            //提交订单或增加购物车数量时（即ids不为空）判断商品库存 —— 注意代码的高度复用巧设计
            if($ids && isset($stocks[$k]) && $stocks[$k] < $v['num']){
                throw new Exception($v['title'].' 的商品库存不足');
            }
            $v['id'] = $k;
            $v['image'] = preg_match('/http:\/\//',$v['image']) ? $v['image'] : request()->domain().$v['image'];
            $v['price'] = $prcie;
            $v['total_price'] = $prcie * $v['num'];
            $v['sku']   = $skusValues[$k] ?? '暂无规则';
            $v['stock'] =  $stocks[$k];
            $result[] = $v;
        }
        if(!empty($result)){
            //按照添加时间排序
            $result = Arr::arrSortByKey($result, 'create_time');
        }


        return $result;
    }

    /**
     * 删除购物车
     * @param $userId
     * @param $id
     * @return bool
     */
    public function deleteRedis($userId, $ids){
        if(!is_array($ids)){
            $ids = explode(',', $ids);
        }
        try {
            // ... 是 PHP提供的一个特性 可变参数 ——使用可变参数实现批量 删除
            $res = Cache::hDel(Key::userCart($userId), ...$ids);
        }catch (\Exception $e){
            return FALSE;
        }
        return $res;
    }
    public function updateRedis($userId, $id, $num){
        try {
            $get = Cache::hGet(Key::userCart($userId), $id);
        }catch (\Exception $e){
            return FALSE;
        }
        if($get){
            $get = json_decode($get,true);
            $get['num'] = $num;
            //注意添加库存判断
            // todo...
        }else{
            throw new Exception('购物车不存在该商品，您的更新没有意义');
        }
        try {
            $res = Cache::hSet(Key::userCart($userId), $id, json_encode($get));
        }catch (\Exception $e){
            return FALSE;
        }
        return $res;
    }
    public function getCount($userId){
        try {
            $count = Cache::hLen(Key::userCart($userId));
        }catch (\Exception $e){
            return 0;
        }
        return intval($count);
    }
}
